package sharetime.core.pager;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import sharetime.core.EntityObject;

public class PagerUtils {

	public static final Logger logger = LoggerFactory.getLogger(PagerUtils.class);

	public static final Pager EMPTY_PAGER = Pager.EMPTY_PAGER;

	public static final String ESCAPEDCOMMA = "ESCAPEDCOMMA";

	@SuppressWarnings("unchecked")
	public static List toList(Pager pager) {
		ArrayList list = new ArrayList();
		for (Iterator iter = pager.iterator(); iter.hasNext();) {
			Object o = iter.next();
			list.add(o);
		}
		return list;
	}

	@SuppressWarnings("unchecked")
	public static int count(Pager pager) {
		Iterator iter = pager.iterator();
		int count = 0;
		while (iter.hasNext()) {
			iter.next();
			count++;
		}
		return count;
	}

	@SuppressWarnings("unchecked")
	public static List toListOfEntityNames(Pager pager) {
		ArrayList list = new ArrayList();
		for (Iterator iter = pager.iterator(); iter.hasNext();) {
			EntityObject e = (EntityObject) iter.next();
			list.add(e);
		}
		return list;
	}

	public static String extractSearchResultName(String distinguishedName) {
		String result = distinguishedName;
		if (StringUtils.isEmpty(distinguishedName))
			return result;
		distinguishedName = distinguishedName.replaceAll("\\\\,",
				"ESCAPEDCOMMA");
		String rdns[] = distinguishedName.split(",");
		boolean invalidDN = true;
		if (rdns.length >= 1) {
			String firstPhrase[] = rdns[0].split("=");
			if (firstPhrase.length >= 2) {
				result = firstPhrase[1].replaceAll("ESCAPEDCOMMA", "\\\\,");
				invalidDN = false;
			}
		}
		if (logger.isDebugEnabled() && invalidDN)
			logger.debug("Could not extract name from search result: "
					+ distinguishedName);
		return result;
	}
}
